const fs = require('fs')
const path = require('path')
const superagent = require('superagent')

function mkImageDir(pathname) {
  return new Promise((resolve, reject) => {
    const fullPath = path.resolve(__dirname, pathname)
    if (fs.existsSync(fullPath)) {
      removeDir(pathname)
    }
    fs.mkdirSync(fullPath)
    console.log(`创建目录${pathname}成功`)
    return resolve()
  })
}

function removeDir(pathname) {
  const fullPath = path.resolve(__dirname, pathname);
  console.log(`${pathname}目录已存在, 准备执行删除`)
  deleteFolderRecursive(fullPath)
  console.log(`历史目录${pathname}删除完成`)
}

function deleteFolderRecursive(url) {
  let files = [];
  /**
   * 判断给定的路径是否存在
   */
  if (fs.existsSync(url)) {
    /**
     * 返回文件和子目录的数组
     */
    files = fs.readdirSync(url);
    files.forEach(function (file, index) {

      const curPath = path.join(url, file);
      /**
       * fs.statSync同步读取文件夹文件，如果是文件夹，在重复触发函数
       */
      if (fs.statSync(curPath).isDirectory()) { // recurse
        deleteFolderRecursive(curPath);

      } else {
        fs.unlinkSync(curPath);
      }
    });
    /**
     * 清除文件夹
     */
    fs.rmdirSync(url);

  } else {
    console.log("给定的路径不存在，请给出正确的路径");
  }
}

function downloadImage(url, name, index, dirName) {
  return new Promise((resolve, reject) => {
    const fullPath = path.resolve(__dirname, dirName, `${index}-.png`)
    if (fs.existsSync(fullPath)) {
      return reject(`文件已存在，跳过此步骤：${name}`)
    }
    superagent.get(url).end((err, res) => {
      if (err) {
        return reject(err)
      }
      fs.writeFile(fullPath, res.body, 'binary', (err) => {
        if (err) {
          return reject(err)
        }
        return resolve(res.body)
      })
    })

  })
}
// 从htmltext中获取数据
function getValueListByReg(str, key) {
  const reg = new RegExp(`"${key}":"(.*?)"`, 'g')
  const matchResult = str.match(reg)
  const resList = matchResult.map(item => {
    const imageUrl = item.match(/:"(.*?)"/g)
    return RegExp.$1
  })
  return resList
}


function request(url, headers) {
  return new Promise((resolve, reject) => {
    superagent
      .get(url)
      .set(headers)
      .end((err, res) => {
        if (err) {
          return reject(`访问失败  错误== ${err}`)
        }
        resolve(res)
      })
  })
}

module.exports = {
  removeDir,
  downloadImage,
  mkImageDir,
  request,
  getValueListByReg
}